// ==UserScript==
// @name         随机抽取检查对象和执法人员控制器
// @namespace    http://tampermonkey.net/
// @version      1.1
// @description  自动控制随机抽取过程，直到匹配到指定执法人员或检查对象
// @author       Yang yang
// @match        http://19.144.5.215:8080/ssj/ssj/planTaskCc/select_*_list.jsp*
// @grant        none
// @run-at       document-idle
// ==/UserScript==

// ==UserScript==
// @name         执法人员/单位抽取控制器
// @namespace    http://tampermonkey.net/
// @version      2.0
// @description  支持执法人员精确匹配和单位模糊匹配的抽取控制
// @author       You
// @match        http://19.144.5.215:8080/ssj/*
// @grant        none
// @run-at       document-idle
// ==/UserScript==

(function() {
    'use strict';

    // 等待页面主要元素加载完成
    const checkExist = setInterval(function() {
        const extractButton = document.getElementById('random');
        if (document.body && extractButton) {
            clearInterval(checkExist);
            initControlPanel();
        }
    }, 500);

    function initControlPanel() {
        // 创建UI元素
        const controlPanel = document.createElement('div');
        controlPanel.id = 'extractionControlPanel';
        controlPanel.style.position = 'fixed';
        controlPanel.style.top = '20px';
        controlPanel.style.right = '20px';
        controlPanel.style.zIndex = '9999';
        controlPanel.style.backgroundColor = '#f5f9ff';
        controlPanel.style.padding = '15px';
        controlPanel.style.border = '2px solid #4a86e8';
        controlPanel.style.borderRadius = '8px';
        controlPanel.style.boxShadow = '0 4px 12px rgba(0,0,0,0.15)';
        controlPanel.style.fontFamily = '"Microsoft YaHei", sans-serif';
        controlPanel.style.maxWidth = '350px';
        controlPanel.style.minWidth = '300px';

        const title = document.createElement('h3');
        title.textContent = '抽取控制面板';
        title.style.marginTop = '0';
        title.style.color = '#1c4587';
        title.style.borderBottom = '1px solid #c9daf8';
        title.style.paddingBottom = '8px';
        title.style.marginBottom = '15px';

        // 抽取类型选择
        const typeLabel = document.createElement('div');
        typeLabel.textContent = '抽取类型:';
        typeLabel.style.marginBottom = '8px';
        typeLabel.style.fontWeight = 'bold';
        typeLabel.style.color = '#444';

        const typeSelector = document.createElement('select');
        typeSelector.id = 'extractionType';
        typeSelector.style.width = '100%';
        typeSelector.style.padding = '6px';
        typeSelector.style.marginBottom = '15px';
        typeSelector.style.border = '1px solid #9fc5e8';
        typeSelector.style.borderRadius = '4px';
        typeSelector.style.backgroundColor = 'white';

        const optionPerson = document.createElement('option');
        optionPerson.value = 'person';
        optionPerson.textContent = '执法人员';

        const optionCompany = document.createElement('option');
        optionCompany.value = 'company';
        optionCompany.textContent = '检查对象';

        typeSelector.appendChild(optionPerson);
        typeSelector.appendChild(optionCompany);

        // 根据页面标题设置默认类型
        const isCompanyPage = document.title.includes('待抽查对象') ||
                             document.title.includes('随机抽取检查对象');
        typeSelector.value = isCompanyPage ? 'company' : 'person';

        // 输入区域
        const inputContainer = document.createElement('div');
        inputContainer.style.marginBottom = '15px';

        const label = document.createElement('div');
        label.id = 'inputLabel';
        label.style.marginBottom = '8px';
        label.style.fontWeight = 'bold';
        label.style.color = '#444';

        const nameInput = document.createElement('input');
        nameInput.type = 'text';
        nameInput.id = 'targetInput';
        nameInput.style.width = '100%';
        nameInput.style.padding = '8px';
        nameInput.style.border = '1px solid #9fc5e8';
        nameInput.style.borderRadius = '4px';
        nameInput.style.boxSizing = 'border-box';

        // 根据类型设置默认提示
        updateInputLabel(typeSelector.value);

        inputContainer.appendChild(label);
        inputContainer.appendChild(nameInput);

        // 状态显示
        const statusDiv = document.createElement('div');
        statusDiv.id = 'extractionStatus';
        statusDiv.style.fontSize = '14px';
        statusDiv.style.margin = '10px 0';
        statusDiv.style.padding = '8px';
        statusDiv.style.borderRadius = '4px';
        statusDiv.style.backgroundColor = '#eaf2ff';
        statusDiv.style.color = '#333';
        statusDiv.innerHTML = '<b>状态:</b> 等待开始...';

        // 按钮
        const startButton = document.createElement('button');
        startButton.textContent = '开始抽取';
        startButton.id = 'startButton';
        startButton.style.backgroundColor = '#4a86e8';
        startButton.style.color = 'white';
        startButton.style.border = 'none';
        startButton.style.padding = '10px 20px';
        startButton.style.borderRadius = '4px';
        startButton.style.cursor = 'pointer';
        startButton.style.fontWeight = 'bold';
        startButton.style.transition = 'background-color 0.3s';
        startButton.style.width = '48%';
        startButton.style.marginRight = '4%';

        const stopButton = document.createElement('button');
        stopButton.textContent = '停止';
        stopButton.id = 'stopButton';
        stopButton.style.backgroundColor = '#cc0000';
        stopButton.style.color = 'white';
        stopButton.style.border = 'none';
        stopButton.style.padding = '10px 20px';
        stopButton.style.borderRadius = '4px';
        stopButton.style.cursor = 'pointer';
        stopButton.style.fontWeight = 'bold';
        stopButton.style.transition = 'background-color 0.3s';
        stopButton.style.width = '48%';

        const buttonContainer = document.createElement('div');
        buttonContainer.style.display = 'flex';
        buttonContainer.style.justifyContent = 'space-between';
        buttonContainer.style.marginTop = '10px';

        buttonContainer.appendChild(startButton);
        buttonContainer.appendChild(stopButton);

        // 组装控制面板
        controlPanel.appendChild(title);
        controlPanel.appendChild(typeLabel);
        controlPanel.appendChild(typeSelector);
        controlPanel.appendChild(inputContainer);
        controlPanel.appendChild(statusDiv);
        controlPanel.appendChild(buttonContainer);

        document.body.appendChild(controlPanel);

        // 状态变量
        let isRunning = false;
        let intervalId = null;
        let targetNames = [];
        let targetKeywords = [];
        let currentType = typeSelector.value;
        let attemptCount = 0;

        // 更新输入标签
        function updateInputLabel(type) {
            if (type === 'person') {
                label.textContent = '输入目标执法人员（逗号分隔）:';
                nameInput.placeholder = '例: 陈伟志,陈楚阳,杨华旭';
            } else {
                label.textContent = '输入单位名称关键词（模糊匹配）:';
                nameInput.placeholder = '例: 万聚';
            }
        }

        // 监听类型选择变化
        typeSelector.addEventListener('change', function() {
            currentType = this.value;
            updateInputLabel(currentType);
        });

        // 更新状态显示
        function updateStatus(message, isError = false) {
            statusDiv.innerHTML = `<b>状态:</b> ${message}`;
            statusDiv.style.color = isError ? '#cc0000' : '#333';
            statusDiv.style.backgroundColor = isError ? '#ffebeb' : '#eaf2ff';
        }

        // 获取表格中的姓名或单位名称
        function getTableData() {
            let selector, index;

            if (currentType === 'person') {
                // 执法人员页面：姓名在第一列
                selector = '.right-box2 table tbody tr td:first-child span';
                index = 0;
            } else {
                // 单位页面：单位名称在第三列
                selector = '.right-box2 table tbody tr td:nth-child(3) span';
                index = 2;
            }

            const cells = document.querySelectorAll(selector);
            const items = [];

            cells.forEach(cell => {
                const text = cell.textContent.trim();
                if (text) items.push(text);
            });

            return items;
        }

        // 检查是否匹配
        function checkMatch() {
            const currentItems = getTableData();

            if (currentType === 'person') {
                // 执法人员：需要完全匹配所有姓名
                if (currentItems.length !== targetNames.length) {
                    return false;
                }

                // 检查是否包含所有目标姓名（忽略顺序）
                return targetNames.every(name => currentItems.includes(name));
            } else {
                // 单位：模糊匹配 - 只要有一个单位包含关键词就算匹配
                if (targetKeywords.length === 0) return false;

                for (const item of currentItems) {
                    const lowerItem = item.toLowerCase();

                    // 检查是否包含所有关键词
                    const containsAll = targetKeywords.every(keyword =>
                        lowerItem.includes(keyword.toLowerCase())
                    );

                    if (containsAll) return true;
                }

                return false;
            }
        }

        // 点击随机抽取按钮
        function clickExtractButton() {
            const extractButton = document.getElementById('random');
            if (extractButton) {
                extractButton.click();
                return true;
            }
            return false;
        }

        // 开始抽取过程
        function startExtraction() {
            const inputValue = nameInput.value.trim();
            if (!inputValue) {
                updateStatus('请输入目标内容', true);
                return;
            }

            if (currentType === 'person') {
                // 执法人员：逗号分隔
                targetNames = inputValue.split(/[，,]/).map(name => name.trim()).filter(name => name);

                if (targetNames.length === 0) {
                    updateStatus('请输入至少一个执法人员姓名', true);
                    return;
                }
            } else {
                // 单位：空格分隔多个关键词
                targetKeywords = inputValue.split(' ').map(kw => kw.trim()).filter(kw => kw);

                if (targetKeywords.length === 0) {
                    updateStatus('请输入至少一个关键词', true);
                    return;
                }
            }

            isRunning = true;
            attemptCount = 0;

            const targetDesc = currentType === 'person'
                ? `执法人员: ${targetNames.join(', ')}`
                : `单位关键词: ${targetKeywords.join(' & ')}`;

            updateStatus(`开始抽取，目标: ${targetDesc}`);

            // 每次尝试间隔5秒
            intervalId = setInterval(() => {
                if (!isRunning) return;

                attemptCount++;

                // 先检查当前页面是否已经匹配
                if (checkMatch()) {
                    stopExtraction();
                    updateStatus(`匹配成功！在${attemptCount}次尝试后找到目标`);
                    return;
                }

                const clicked = clickExtractButton();
                if (!clicked) {
                    updateStatus('找不到抽取按钮', true);
                    stopExtraction();
                    return;
                }

                updateStatus(`尝试中... (第${attemptCount}次)`);

                // 在AJAX加载后检查匹配
                setTimeout(() => {
                    if (checkMatch()) {
                        stopExtraction();
                        updateStatus(`匹配成功！在${attemptCount}次尝试后找到目标`);
                    }
                }, 2000); // 等待3秒让数据加载
            }, 3000);

            // 立即执行第一次尝试
            clickExtractButton();
            updateStatus('尝试中... (第1次)');
            attemptCount = 1;
        }

        // 停止抽取过程
        function stopExtraction() {
            isRunning = false;
            if (intervalId) {
                clearInterval(intervalId);
                intervalId = null;
            }
        }

        // 按钮事件绑定
        startButton.addEventListener('click', () => {
            if (!isRunning) {
                startExtraction();
            }
        });

        stopButton.addEventListener('click', () => {
            if (isRunning) {
                stopExtraction();
                updateStatus('已停止');
            }
        });

        // 初始化时更新状态
        const initialItems = getTableData();
        if (initialItems.length > 0) {
            updateStatus(`当前${currentType === 'person' ? '执法人员' : '单位'}: ${initialItems.join(', ')}`);
        }
    }
})();